import router from '../router/index.js';
const modules = import.meta.glob('../view/*/*.vue');
/* 转化为树形结构 */
export const routerTotree = (data) => {
    let children = data.filter(item => item.pid !== 0);
    let parents = data.filter(item => item.pid === 0);
    totree(parents, children)
    function totree(parents, childen) {
        parents.forEach(p => {
            childen.forEach((c, index) => {
                if (p.id === c.pid) {
                    /* 移除c的意向 */
                    let _c = JSON.parse(JSON.stringify(childen));
                    _c.splice(index, 1);
                    totree([c], _c);
                    if (p.children) {
                        p.children.push(c);
                    } else {
                        p.children = [c];
                    }
                }
            })
        })
    }
    return parents;
}
/* 转化为路由 */
export const generateRouter = (data) => {
    let newRouters = data.map(item => {
        let routers = {
            path: item.path,
            name: item.name,
            meta: item.meta,
            link: item.link
        }
        item.redirect ? routers["redirect"] = item.redirect : ""
        if (item.children && item.children.length > 0) {
            routers.children = generateRouter(item.children)
        }
        return routers
    })
    return newRouters
}
/* 转化为菜单 */
export const getMenulist = (data) => {
    let menulist = []
    for (let i = 0; i < data.length; i++) {
        let item = data[i];
        let menuitem = {
            name: item.meta.routername,
            path: item.path,
        }
        if (item.children && item.children.length > 0) {
            menuitem["is"] = true;
            menuitem["children"] = getMenulist(item.children)
        }
        if (item.meta.isshow) {
            menulist.push(menuitem)
        }
    }
    return menulist
}
/* 动态添加路由 */
export const dealWithRoute = (list, parents = "index") => {
     for (let data of list) {
       if (data.children && data.children.length > 0) {
            let route = {
                path: data.path,
                name: data.name,
                meta: data.meta
            }
            if(data.link){
                let url = `../view/${data.link}`
                route["component"] = modules[url]
            }
            data.redirect ? route["redirect"] = data.redirect : ""
            router.addRoute(parents, route)
            dealWithRoute(data.children, data.name)
        } else {
            let route ={
                path: data.path,
                name: data.name,
                meta: data.meta
            }
            
            let url = `../view/${data.link}`
            route["component"] = modules[url]

            router.addRoute(data.meta.parentname,route)
        }
    } 
}   